package com.txf.coomon.net.net_retrofit;

import android.content.Context;

import com.txf.coomon.net.net_retrofit.listener.AppRequestListener;
import com.txf.other_toolslibrary.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * @author txf
 * @create 2019/1/31 0031
 * @观察者
 */

public class ProgressObserver<T> implements Observer<T> {

    private Context context;
    private AppRequestListener listener;
    private boolean isDialog;
    private boolean cancelable;
    private Disposable disposable;

    public <T> ProgressObserver(Context context, AppRequestListener<T> listener, boolean isDialog, boolean cancelable) {
        this.context = context;
        this.listener = listener;
        this.isDialog = isDialog;
        this.cancelable = cancelable;

    }

    @Override
    public void onSubscribe(Disposable d) {
        disposable = d;
    }

    @Override
    public void onNext(T t) {
        listener.onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof UnknownHostException) {
            ToastUtils.show("没有网络，请检查网络连接");
        } else if (e instanceof SocketTimeoutException) {
            ToastUtils.show("请求超时");
        } else if (e instanceof ConnectException) {
            ToastUtils.show("服务器连接失败，请稍后重试");
        } else if (e instanceof HttpException) {
            ToastUtils.show("请求超时");
        } else if (e instanceof UnknownServiceException) {
            ToastUtils.show("未知的服务器错误");
        } else {
            ToastUtils.show("服务器错误，请稍后重试");
        }
    }

    @Override
    public void onComplete() {
        if (!disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
